//$URL: http://dasding.googlecode.com/svn/branches/testzeugs/demos/jax-rs-springsecurity/src/main/java/de/piratech/jaxrs/security/MySecurityContext.java $
//$Id: MySecurityContext.java 55 2012-10-16 11:57:28Z amuthmann@gmail.com $
package de.piratech.jaxrs.security;

import java.security.Principal;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

/**
 * @author "Animesh Kumar <animesh@strumsoft.com>"
 *
 */
public class MySecurityContext implements javax.ws.rs.core.SecurityContext {

  private final User user;

  public MySecurityContext(User user) {
    this.user = user;
  }

  @Override
  public String getAuthenticationScheme() {
    return SecurityContext.BASIC_AUTH;
  }

  @Override
  public Principal getUserPrincipal() {
    return user;
  }

  @Override
  public boolean isSecure() {
    return user != null;
  }

  @Override
  public boolean isUserInRole(String role) {

    if (user == null) {
      // Forbidden
      Response denied = Response.status(Response.Status.FORBIDDEN).entity("Permission Denied").build();
      throw new WebApplicationException(denied);
    }

    try {
      // this user has this role?
      return user.getRoles().contains(User.Role.valueOf(role));
    }
    catch (Exception e) {
    }

    return false;
  }
}